<!DOCTYPE html>
<html lang="en"
      xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorator="/web/_layouts/default">
<head>
    <meta charset="UTF-8">
    <title>爱天气</title>
</head>
<body>
<!--登陆和注册模块-->
<div id="pjax-web-container" layout:fragment="content">
    <!--<div id="loader-wrapper">-->
        <!--<div class="loader">-->
            <!--<div class="ball-clip-rotate-pulse">-->
                <!--<div></div>-->
                <!--<div></div>-->
            <!--</div>-->
        <!--</div>-->
    <!--</div>-->
    <main class="g-main">
        <div class="container">
            <div class="row">
                <div class="g-weather-card col-sm-7 col-sm-offset-2">
                    <form id="query" method="POST" action="/">
                        <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
                        <div class="search-wrapper pull-right">
                            <div class="search-box">
                                <div class="search-widget">
                                    <input id="search-input" type="text" placeholder="城市搜索" autocomplete="off"
                                           th:value="${city}">
                                    <input id="city-id" name="city" type="hidden" th:value="${cityId}">
                                    <div class="search-btn">
                                    <span class="icon" onclick="submit()">
                                        <svg focusable="false" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path
                                                d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path></svg>
                                    </span>
                                    </div>
                                </div>
                                <div class="search-tips">
                                    <ul style="overflow-y: scroll; max-height: 6em;">
                                        <li><!--福建, 泉州, 南安--></li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </form>
                    <div class="h g-color location" th:text="${city}"></div>
                    <div class="g-color date-time">星期一 7:00 AM</div>
                    <div>
                        <span class="g-color sh description">小雨</span>
                    </div>
                    <!--天气图标-->
                    <div style="font:16px arial,helvetica,sans-serif;padding:20px 0 0;-webkit-touch-callout:none;-webkit-user-select:none">
                        <div class="weather-box">
                            <img class="g-weather-img j-img"
                                 src="//ssl.gstatic.com/onebox/weather/64/rain_s_cloudy.png">
                            <div class="g-weather-temp-box">
                                <div>
                                    <div class="g-weather-tmp">
                                        <span class="temp">21</span>
                                    </div>
                                    <div class="g-weather-unit">
                                        <!--<span style="display: none;" aria-label="°Fahrenheit">°F</span>-->
                                        <!--<a href="#">-->
                                        <!--<span aria-label="°Fahrenheit">°F</span></a>&nbsp;|-->
                                        <span aria-label="°Celsius">°C</span>
                                    </div>
                                </div>
                            </div>
                            <div class="g-weather-panel g-color">
                                <div>降雨量: <span class="rain">30%</span></div>
                                <div>湿度: <span class="humidity">68%</span></div>
                                <div>风速: <span class="wind">19 km/h</span></div>
                                <div class="g-weather-btn-group ">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="clear-both"></div>

                    <!--天气图表-->
                    <div id="main" class="col-sm-12" style="height:230px;"></div>
                    <!--天气预报-->
                    <div class="g-weather-forecast col-sm-12"
                         style="overflow-x: scroll">
                        <div class="g-weather-forecast-card-group">

                            <!-- JS .append-->

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
    <div class="g-download-panel">
        <div class="container">
            <hr class="half-rule">
            <h2>下载体验</h2>
            <p class="lead">提供了 Web、macOS、Chrome 供用户进行体验。</p>
            <hr class="half-rule">
            <div class="row">
                <div class="col-sm-4">
                    <img th:src="@{/web-lte/img/weather-chrome.png}" alt="" class="img-responsive"
                         style="margin: 0 auto;">
                    <h3 style="margin-top: 0;">Chrome</h3>
                    <p class="c-gy">
                        Chrome 插件&nbsp;
                        <a href="http://olnbke6s0.bkt.clouddn.com/WearthForChrome2.crx"
                           rel="nofollow">
                            <i class="fa fa-download"></i>
                        </a>
                    </p>
                    <p>

                        <a href="https://chrome.google.com/webstore/detail/weather/ibieofighcnndjcjchdahdiacjpmkhgf"
                           rel="nofollow"><img
                                src="https://camo.githubusercontent.com/da9d119ebd0019c0dac7fd2d667ece5d764c0a20/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4368726f6d6525323057656225323053746f72652d76302e302e372d627269676874677265656e2e737667"
                                alt="Chrome Web Store"
                                data-canonical-src="https://img.shields.io/badge/Chrome%20Web%20Store-v0.0.7-brightgreen.svg"
                                style="max-width:100%;"></a>
                    </p>
                </div>
                <div class="col-sm-4">
                    <img th:src="@{/web-lte/img/weather-macOS.png}" alt="" class="img-responsive"
                         style="margin: 0 auto;">
                    <h3 style="margin-top: 0;">macOS</h3>
                    <p class="c-gy">
                        macOS 软件&nbsp;
                        <a href="http://olnbke6s0.bkt.clouddn.com/WearthForMac2.dmg"
                           rel="nofollow">
                            <i class="fa fa-download"></i>
                        </a>
                    </p>
                </div>
                <div class="col-sm-4">
                    <img th:src="@{/web-lte/img/web.png}" alt="" class="img-responsive"
                         style="margin: 0 auto;">
                    <h3 style="margin-top: 0;">Web</h3>
                    <p class="c-gy">
                        即使方便浏览实时天气..
                    </p>
                </div>
            </div>
            <hr class="half-rule">
        </div>
    </div>
    <script type="text/javascript" th:inline="javascript">


        /*<![CDATA[*/
        var lon = /*[[${lon}]]*/ '';
        var lat = /*[[${lat}]]*/ '';

        function locationBefore(callback) {
            if (navigator.geolocation && !lon && !lat) { // 支持定位
                navigator.geolocation.getCurrentPosition(function (position) {
                    lat = position.coords.latitude;
                    lon = position.coords.longitude;
                    callback(lat.toFixed(3), lon.toFixed(3));
                }, function (error) {
                    callback(24.636, 118.074);
                    console.log('[错误日志] Error occurred. Error code: ' + error.code);
                    // error.code can be:
                    //   0: unknown error
                    //   1: permission denied
                    //   2: position unavailable (error response from locaton provider)
                    //   3: timed out
                });
            } else {
                callback(lat, lon);
            }
        }

        /*]]>*/

        function done() {
            if (!$('body').hasClass('loaded')) {
                $('body').removeClass('loading')
                    .addClass('loaded');
            }
            $('#loader-wrapper').hide().remove();
        }

        function submit() {
            if (!!$('#city-id').val()) {
                $('form#query').submit();
            } else {
                layer.msg('请选择城市', {icon: 2});
            }
        }

        $(document).ready(function () {
            var myChart = echarts.init(document.getElementById('main'));
            var $forecastCardGroup = $('.g-weather-forecast-card-group');
            var $forecastCard = $('.g-weather-forecast-card');
            var $location = $('.location');
            var list = null;
            locationBefore(function (lat, lon) {
                // 当前天气
                $.post('/public/weather/current', {
                    lon: lon,
                    lat: lat,
                    units: 'metric'
                }, function (data) {
                    if (data.code === 200) {
                        var data = data.data;
                        if (!$location.text()) {
                            $location.text('中国, ' + data.name);
                        }
                        setWeatherInfo(
                            data.main.temp,
                            data.wind.speed,
                            data.sys.message,
                            data.main.humidity,
                            data.weather[0].icon,
                            data.dt,
                            data.weather[0].description);
                    } else {
                        layer.msg(data.message)
                    }
                });
                // 天气预报
                $.post('/public/weather/forecast', {
                    lon: lon,
                    lat: lat,
                    units: 'metric'
                }, function (data) {
                    // done();
                    if (data.code === 200) {
                        /**
                         * 温度
                         * 湿度
                         * 可见度
                         * 时间
                         */
                        var dtArr = [];
                        var tempArr = [];
                        var rain3hArr = [];
                        var days = [];
                        /**
                         * all: 37
                         * 2017-11-24: 5
                         * 2017-11-25: 5
                         * 2017-11-26: 5
                         **/
                        var progress = {
                            all: 0,
                            dates: []
                        };
                        $.each(list = data.data.list, function (index, obj) {
                            /**
                             * 每天的第一个
                             */
                            var date = obj.dt_txt.substring(0, 10); // "2017-11-24 09:00:00" => "2017-11-24"
                            progress.all += 1;
                            if ($.inArray(date, days) === -1) {
                                progress.dates.push(date);
                                progress[date] = 1;
                                days.push(date);
                                var forecastCardNode = '<div class="g-weather-forecast-card" data-date="' + date + '" data-start="' + (progress.all - 1) + '">\n' +
                                    '                                <div class="g-weak g-color">' + DateKit.getCnDay(new Date(obj.dt_txt)) + '</div>\n' +
                                    '                                <div class="inline-block">\n' +
                                    '                                    <img class="g-img" src="' + Google.getIconSrc(obj.weather[0].icon) + '">\n' +
                                    '                                </div>\n' +
                                    '                                <div class="g-temp">\n' +
                                    '                                    <div class="inline-block pr5">\n' +
                                    '                                        <span>' + Math.floor(obj.main.temp_max) + '</span>°\n' +
                                    '                                    </div>\n' +
                                    '                                    <div class="inline-block g-color">\n' +
                                    '                                        <span>' + Math.floor(obj.main.temp_min) + '</span>°\n' +
                                    '                                    </div>\n' +
                                    '                                </div>\n' +
                                    '                            </div>';
                                $forecastCardGroup.append(forecastCardNode);
                            } else {
                                progress[date] += 1;
                            }

                            // 预测时间
                            var time = parseInt(obj.dt_txt.substring(11, 13));// "2017-11-24 09:00:00" => "09:00"
                            if (time >= 12) {
                                time %= 12;
                                time += ' PM';
                            } else {
                                time += ' AM';
                            }
                            dtArr.push(time);
                            // 预测温度
                            tempArr.push(obj.main.temp);
                            rain3hArr.push(!!obj.rain ? obj.rain._$3h : 0);
                        });
                        $forecastCard = $('.g-weather-forecast-card');
                        $.each($forecastCard, function (index, card) {
                            var $card = $(card);
                            var date = $card.data('date');
                            $card.data('all', progress.all);
                            $card.data('val', progress[date]);
                        });

                        var option = {
                            title: {
//                text: '天气预报'
                            },
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'cross',
                                    crossStyle: {
                                        color: '#999'
                                    }
                                }
                            },
                            toolbox: {
                                feature: {
                                    saveAsImage: {
                                        show: true
                                    }
                                }
                            },
                            dataZoom: [
                                {   // 这个dataZoom组件，默认控制x轴。
                                    type: 'slider', // 这个 dataZoom 组件是 slider 型 dataZoom 组件
                                    start: 0,      // 左边在 10% 的位置。
                                    end: 100          // 右边在 60% 的位置。
                                }
                            ],
                            legend: {
                                data: ['温度', '降水量']
                            },
                            color: [
                                '#4270f4',
                                '#f7cf09'
                            ],
                            xAxis: [{
                                type: 'category',
                                data: dtArr
                            }],
                            yAxis: [{
                                type: 'value',
                                name: '降水量',
                                min: function (value) {
                                    var val = value.min - 2;
                                    return Math.ceil(val < 0 ? 0 : val);
                                },
                                max: 'dataMax',
                                splitNumber: 3,
                                axisLabel: {
                                    formatter: '{value} ml'
                                }
                            }, {
                                type: 'value',
                                name: '温度',
                                min: function (value) {
                                    return Math.ceil(value.min - 2);
                                },
                                max: function (value) {
                                    return Math.ceil(value.max + 2);
                                },
                                splitNumber: 3,
                                axisLabel: {
                                    formatter: '{value} °C'
                                }
                            }],
                            series: [{
                                name: '降水量',
                                type: 'bar',
                                yAxisIndex: 0,
                                data: rain3hArr
                            }, {
                                name: '温度',
                                type: 'line',
                                smooth: true,
                                yAxisIndex: 1,
                                data: tempArr
                            }]
                        };
                        myChart.setOption(option);
                    } else {
                        layer.msg(data.message);
                    }
                });
            });
            /**
             * 选中星期的事件
             */
            $(document).on('click', '.g-weather-forecast-card', function ($e) {
                $forecastCard.removeClass('active');
                var $this = $(this);
                $this.addClass('active');
                var start = $this.data('start');
                var all = $this.data('all');
                var val = $this.data('val');
                myChart.dispatchAction({
                    type: 'dataZoom',
                    // 可选，dataZoom 组件的 index，多个 dataZoom 组件时有用，默认为 0
                    dataZoomIndex: 0,
                    // 开始位置的百分比，0 - 100
                    start: (start / all) * 100,
                    // 结束位置的百分比，0 - 100
                    end: ((start + val) / all) * 100
                })
            });

            myChart.on('mousemove', function (params) {
                if (!!list) {
                    var data = list[params.dataIndex];
                    setWeatherInfo(
                        data.main.temp,
                        data.wind.speed,
                        !!data.rain ? data.rain._$3h : 0,
                        data.main.humidity,
                        data.weather[0].icon,
                        data.dt_txt,
                        data.weather[0].description
                    )
                }
            });

            var $weatherBox = $('.weather-box');
            var $description = $('.description');
            var $dateTime = $('.date-time');
            var $j_img = $('.j-img');

            function setWeatherInfo(temp, windSpeed, rain, humidity, img, dt_txt, description) {
                $weatherBox.find('.temp').text(Math.floor(temp));
                $weatherBox.find('.wind').text(windSpeed + ' km/h');
                $weatherBox.find('.rain').text((rain + '').substring(0, 6) + ' ml');
                $weatherBox.find('.humidity').text(humidity + '%');
                $description.text(description);
                var date = new Date(dt_txt);
                $j_img[0].src = Google.getIconSrc(img);
                $dateTime.text(DateKit.getCnDay(date) + ' ' + DateKit.getTimeAM_PM(date));
            }

            /**
             * 搜索相关
             */

                // 监听文字输入
            var $searchInput = $('#search-input');
            $searchInput.on('input propertychange', function () {
                var $searchTips = $('.search-tips');
                if (!$searchTips.hasClass('active')) {
                    var width = $('.search-box').width();
                    $searchTips.css('min-width', width).addClass('active')
                }
                $.post('/public/city/search', {q: $(this).val()}, function (data) {
                    $('.search-tips ul').empty();
                    if (data.code === 200) {
                        $.each(data.data, function (index, obj) {
                            $('.search-tips ul').append('<li data-id="' + obj.id + '">' + obj.province + ', ' + obj.city + ', ' + obj.county + '</li>');
                        });
                    }
                });
            });
            $(document).on('mouseover', '.search-tips li', function () {
                var $this = $(this);
                $searchInput.val($this.text());
                $('#city-id').val($this.data('id'));
            }).on('click', '.search-tips li', function () {
                submit();
            }).on('mouseleave', '.search-tips', function () {
                $('.search-tips ul').empty();
            });
        });
    </script>
</div>

</body>
</html>